﻿//using CommonProjects.AntiFake;
//using CommonProjects.FaceDetetive.Algorithm.QianS.v3;
//using Emgu.CV;
//using Emgu.CV.CvEnum;
//using Emgu.CV.Structure;
using FaceCoreBase.Models;
//using FaceTrackerAlgorithm;
using PluginService.Common;
using PluginService.Common.Model;
using PluginService.Common.Sockets;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
//using CommonProjects.Extensions;
using System.Drawing.Imaging;

namespace FaceDetectiveWindowsService
{

    public class ImageDatas
    {
        public byte[] ImageArray { get; set; }

        public int Width { get; set; }

        public int Height { get; set; }

        public int Stride { get; set; }
    }

    public class FaceDeteiveHelper
    {
        #region 变量

        //protected FaceTrackerNetAPI _faceTracker = null;

        //protected WisFacePointsAPI _wisFacePointAPI = null;

        const int MAXFACE_NUM = 1,PORT=4502;

        //protected McBaseFaceDeteiveAlgorithmV3 _faceDeteive = null;

        protected AsyncFaceDeteiveSocketServer _faceDeteiveSocketServer;

        [DllImport("WisFaceEngineWrap.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int qs_Wis_Create();

        [DllImport("WisFaceEngineWrap.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int qs_Wis_DetectFaces(int engine, [In, MarshalAs(UnmanagedType.LPArray)] byte[] rgb24, int width, int height, int widthstep,
            [Out, MarshalAs(UnmanagedType.LPArray)]FaceFeatureRectangle[] rects, int maxFaceCount);


        [DllImport("wisfacepoints.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int CreateFacePointsEngine();

        [DllImport("wisfacepoints.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern float CalculateFacePoints(int engine, 
            IntPtr rgb24, int width, int height, int widthstep, IntPtr rtFace,
             IntPtr fpm);
        //public static extern float CalculateFacePoints(int engine, [In, MarshalAs(UnmanagedType.LPArray)]byte[] rebdata24, int width, int height, int widthstep, FaceFeatureRectangle rtFace,
        //     out QSFacePointsModel fpm);

        //HaarCascade _emgu;

        int _wisPtr = 0;

        #endregion

        #region 公共方法

        public void Init()
        {
            //if (_faceTracker == null)
            //{
            //    _faceTracker = new FaceTrackerNetAPI(MAXFACE_NUM);
            //    _faceTracker.Init();
            //}

            //if (_faceDeteive == null)
            //{
            //    _faceDeteive = new McBaseFaceDeteiveAlgorithmV3();
            //    _faceDeteive.Init();
            //}

            //if (_emgu == null)
            //{
            //    _emgu = new HaarCascade(string.Format("{0}{1}",
            //        Util.GetWindowsServiceInstallPath("FaceDeteiveService").Replace("FaceDetectiveWindowsService.exe", ""), "haarcascade_frontalface_alt.xml"));
            //}

            //if (_wisFacePointAPI == null)
            //{
            //    _wisFacePointAPI = new WisFacePointsAPI();
            //    _wisFacePointAPI.Init();
            //    if (!_wisFacePointAPI.IsCreateEngineSuccess)
            //    {
            //        throw new Exception("facepoint create failed");
            //    }
            //}

            _wisPtr = CreateFacePointsEngine();

            if(_faceDeteiveSocketServer==null)
            {
                _faceDeteiveSocketServer = new AsyncFaceDeteiveSocketServer(PORT, 10);
                _faceDeteiveSocketServer.OnConnectedServer += FaceDeteiveSocketServer_OnConnectedServer;
                _faceDeteiveSocketServer.OnReceivedMessage += FaceDeteiveSocketServer_OnReceivedMessage;
                _faceDeteiveSocketServer.InitSocket();
                
            }
        }

       

        public void Start()
        {
            if (_faceDeteiveSocketServer != null)
            {
                _faceDeteiveSocketServer.Listen();
            }
        }

        #endregion

        #region 重写方法

        private static Bitmap Base64StringToImage(string txtFileName)
        {
            String inputStr = txtFileName;
            byte[] arr = Convert.FromBase64String(inputStr);
            MemoryStream ms = new MemoryStream(arr);
            Bitmap bmp = new Bitmap(ms);
            ms.Close();
            return bmp;
            //MessageBox.Show("转换成功！");

        }

        public static byte[] BitmapToByteArray(Bitmap bitmap, out int stride)
        {

            BitmapData bmpdata = null;
            stride = 0;
            try
            {
                //bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
                bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
                int numbytes = bmpdata.Stride * bitmap.Height;
                byte[] bytedata = new byte[numbytes];
                IntPtr ptr = bmpdata.Scan0;

                Marshal.Copy(ptr, bytedata, 0, numbytes);
                stride = bmpdata.Stride;
                return bytedata;
            }
            finally
            {
                if (bmpdata != null)
                    bitmap.UnlockBits(bmpdata);
            }

        }

        protected virtual void FaceDeteiveSocketServer_OnReceivedMessage(AsyncMessageHandleArgs<byte[]> args)
        {
            string str = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCADwAUADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6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wUuclpG5P0FX9Umvdc1GS5dSVPC5OFVf8AGol0qFGzcTnPUhRn9TQkA6HTrCJcu5mPUkkAVNvs1G1IocDp8uTTG0yydcCZx+Oc/pWbeaNMoL2r+aAPoaAsaE8dnMMSwbfdRgj8qx9Q0sxoZLVvMQdscj/GoYtQu7ZtrMSBxskHH+IrUsdRtrhgpHkyHpz8pNGmwHLMCT1PHWkaUfZmifPB3D29f6V0Ot6WX3TwqA4HzqP4h6j3rmiM5yD09Kl6AijKSzFgCR6+1MHIzk4qf7pK+nSrltHGygMgJ9fWi+lh20M/tzTeuSfzroYdMtXXLhl9CGpk2jQ7fkdgfzyKBHONxnk9aj/PPWtW80p41LJIrDr0xWbJEyZBU5+lCGhinI45FB/rTfpnrRn1/PFFx8oqsTn9Kcp+XgcjvUYB5HtUgGOAen40XQrDlHJwfenheDgj/GmorHOFJI9AasLbznA8p+nB2mi9xDGbsBikOSOMk1ZFhdHOIX/EVZi0t9uZnVMdupNMEUFzjOTSn8eK14bK3UAMu855JPFWTFEg+WFc5646U7AYIRyOAeeM4qWa3mWJZ2VvLdiqtjgsO34Ag/jV69cBNqgDvxXTaJZJq/g/VdPUA3VqVvofVht2sPy7euKVgucW74iI4yevtTFyvHI/WmuxI545xViwtHuZCBhUH3nPQCkOwwHdjZn0xjnNaUFmI0Ml22xccL/Eak860sVIgAklAwZGH9Kzp7h5WLPuLE9M8YzVbEmi2oeUcW6hVHTjn61ELy4Y7txyf0qiinjOCcdOn61bs4ZZpAiIWJOOO1AWLMd3dIp2ufzrStdY1CFSpkDg9Qfr71LZ6OFGbmTJyPlX/GtKOC0TgQL7ZGTTC2h//9k=";
            var bmp = Base64StringToImage(str);
            if (bmp != null)
            {
                int stride=0;
                var data = BitmapToByteArray(bmp, out stride);
                if (data != null)
                {
                    FaceCoreBase.Models.FaceFeatureRectangle rectangle = new FaceCoreBase.Models.FaceFeatureRectangle();
                    rectangle.bottom = 122;
                    rectangle.left = 142;
                    rectangle.right = 212;
                    rectangle.top = 52;
                    IntPtr dataPtr = IntPtr.Zero;
                    dataPtr = Marshal.AllocHGlobal(data.Length);
                    Marshal.Copy(data, 0, dataPtr, data.Length);
                    
                    IntPtr rectanglePtr=Marshal.AllocHGlobal(Marshal.SizeOf(rectangle));
                    Marshal.StructureToPtr(rectangle,rectanglePtr,true);

                    QSFacePointsModel pointModel=new QSFacePointsModel();
                    IntPtr resutPtr = Marshal.AllocHGlobal(Marshal.SizeOf(pointModel));

                    var scoll = CalculateFacePoints(_wisPtr, dataPtr, bmp.Width, bmp.Height, stride, rectanglePtr, resutPtr);
                    Marshal.FreeHGlobal(dataPtr);
                    Marshal.FreeHGlobal(rectanglePtr);
                    Marshal.FreeHGlobal(resutPtr);
                    args.AsyncSocketConnect.AsyncSend(BitConverter.GetBytes(scoll));
                    //var facePoint = _wisFacePointAPI.DetectFacesFeatureFromDbi(data, bmp.Width, bmp.Height, stride, rectangle);
                    //if (facePoint != null)
                    //{
                    //    args.AsyncSocketConnect.AsyncSend(BitConverter.GetBytes(facePoint.facePoints.pitch));
                    //}
                }
               
            }
            

            //if (args != null && args.Msg != null && args.Msg.Length > 12 )
            //{
            //    var imageData = GetImageData(args.Msg);
                
            //    if (imageData != null)
            //    {
            //        //byte[] cloneData = new byte[imageData.ImageArray.Length];
            //        //Array.Copy(imageData.ImageArray, cloneData, cloneData.Length);
            //        IntPtr dataPtr=IntPtr.Zero;

            //        try
            //        {
            //            //var trackerResult = _faceTracker.FaceTracker(imageData.ImageArray, imageData.Width, imageData.Height, imageData.Stride);
            //            //var faceDeteiveResult = _faceDeteive.DetectFaceRectangles(imageData.ImageArray, imageData.Width, imageData.Height, imageData.Stride, 1);
            //            dataPtr = Marshal.AllocHGlobal(imageData.ImageArray.Length);
                        
            //            Marshal.Copy(imageData.ImageArray,0,dataPtr,imageData.ImageArray.Length);
            //            Bitmap bitmap=new Bitmap(imageData.Width,imageData.Height,imageData.Stride,System.Drawing.Imaging.PixelFormat.Format24bppRgb,dataPtr);
            //            Image<Gray, byte> image = new Image<Gray, byte>(bitmap);
                        //var faces = _emgu.Detect(image,
            //    1.2,
            //    3,
            //    HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
            //    new Size(5, 5));
            //            if (faces.Count() > 0)
            //            {

            //                System.Drawing.Rectangle r = faces[0].rect;

            //                FaceCoreBase.Models.FaceFeatureRectangle rectangle = new FaceCoreBase.Models.FaceFeatureRectangle();
            //                rectangle.bottom = r.Bottom;
            //                rectangle.left = r.Left;
            //                rectangle.right = r.Right;
            //                rectangle.top = r.Top;
            //                //args.AsyncSocketConnect.AsyncSend(BitConverter.GetBytes(rectangle.bottom));

            //                var facePoint = _wisFacePointAPI.DetectFacesFeatureFromDbi(image.Bytes, imageData.Width, imageData.Height, imageData.Stride,
            //                    rectangle);
            //                if (facePoint != null)
            //                {
            //                    args.AsyncSocketConnect.AsyncSend(BitConverter.GetBytes(facePoint.facePoints.pitch));
            //                }
            //                image.Dispose();
            //            }
            //        }
            //        catch (Exception ex)
            //        {
            //            args.AsyncSocketConnect.AsyncSend(System.Text.UTF8Encoding.ASCII.GetBytes(ex.Message));
            //        }
            //        finally
            //        {
            //            Marshal.FreeBSTR(dataPtr);
            //        }
                    
            //    }
            //}
        }

        protected virtual void FaceDeteiveSocketServer_OnConnectedServer(AsyncSocketConnect<byte[]> connect)
        {
            //throw new NotImplementedException();
        }

        #endregion

        #region statick

        private static ImageDatas GetImageData(byte[] args)
        {
            ImageDatas result = new ImageDatas();
            result.ImageArray = new byte[args.Length - 12];
            result.Width = BitConverter.ToInt32(args, args.Length - 12);
            result.Height = BitConverter.ToInt32(args, args.Length - 8);
            result.Stride = BitConverter.ToInt32(args, args.Length - 4);
            Array.Copy(args, result.ImageArray, args.Length - 12);
            return result;
        }

        #endregion
    }
}
